package com.longqin.business.service.impl;

import com.longqin.business.entity.BusProject;
import com.longqin.business.entity.BusProjectMember;
import com.longqin.business.entity.BusProjectMilestone;
import com.longqin.business.entity.BusProjectRequirement;
import com.longqin.business.entity.BusRequirement;
import com.longqin.business.mapper.BusProjectMapper;
import com.longqin.business.mapper.BusProjectMemberMapper;
import com.longqin.business.mapper.BusProjectMilestoneMapper;
import com.longqin.business.mapper.BusProjectRequirementMapper;
import com.longqin.business.service.IBusProjectService;
import com.longqin.business.util.OperationLog;
import com.longqin.business.util.RedisUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Calendar;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 项目管理 服务实现类
 * </p>
 *
 * @author longqin
 * @since 2025-01-21
 */
@Service
public class BusProjectServiceImpl extends ServiceImpl<BusProjectMapper, BusProject> implements IBusProjectService {

	@Autowired
	BusProjectMapper busProjectMapper;
	
	@Autowired
	BusProjectMilestoneMapper busProjectMilestoneMapper;
	
	@Autowired
	BusProjectMemberMapper busProjectMemberMapper;
	
	@Autowired
	BusProjectRequirementMapper busProjectRequirmentMapper;
	
	@Autowired
	RedisUtil redisUtil;
	
	private static final String CODE_PREFIX = "XMSQ"; // 项目编码前缀
	private static final String CODE_REDIS_KEY = "project_code"; // 自增项目编码REDIS存储KEY
	
	@Override
    public BusProject getById(int id) {
		BusProject project = busProjectMapper.selectById(id);
		List<BusProjectMilestone> milestones = busProjectMilestoneMapper.selectByProjectId(id);
		if (milestones != null){
			project.setMilestones(milestones.toArray(new BusProjectMilestone[0]));
		}
		List<BusProjectMember> members = busProjectMemberMapper.selectByProjectId(id);
		if (members != null){
			project.setMembers(members.toArray(new BusProjectMember[0]));
		}
		List<BusRequirement> requirements = busProjectRequirmentMapper.selectByProjectId(id);
		if (requirements != null){
			project.setRequirmentList(requirements.toArray(new BusRequirement[0]));
			requirements.stream().map(s -> s.getId()).collect(Collectors.toList());
			project.setRequirments(requirements.stream().map(s -> s.getId()).collect(Collectors.toList()).toArray(new Integer[0]));
		}
		return project;
    }
	
	@Override
    public List<BusProject> getPage(String projectName, int organizationId, int startIndex, int pageSize) {
        return busProjectMapper.selectPage(projectName, organizationId, startIndex, pageSize);
    }
    
	@Override
    public int getCount(String projectName, int organizationId) {
        return busProjectMapper.selectCount(projectName, organizationId);
    }
	
	@OperationLog(title = "删除项目", content = "'项目id：' + #id", operationType = "1")
	@Override
    public int delete(int id) throws Exception {
		return busProjectMapper.updateStatus(0, id);
    }
	
	@OperationLog(title = "创建项目", content = "'项目名称：' + #entity.getProjectName()", operationType = "0")
	@Override
    public int create(BusProject entity) throws Exception {
		entity.setProjectCode(generateCode(CODE_REDIS_KEY));
		int result = busProjectMapper.insert(entity);
		if (result > 0){
			for(BusProjectMilestone milestone : entity.getMilestones()){
				milestone.setProjectId(entity.getId());
				busProjectMilestoneMapper.insert(milestone);
			}
			for(BusProjectMember member : entity.getMembers()){
				for(Integer userId : member.getUserIdArr()){
					BusProjectMember newMember = new BusProjectMember();
					newMember.setMemberType(member.getMemberType());
					newMember.setUserId(userId);
					newMember.setProjectId(entity.getId());
					busProjectMemberMapper.insert(newMember);
				}
			}
			if (null != entity.getRequirments()){
				for(Integer requirmentId : entity.getRequirments()){
					BusProjectRequirement requirement = new BusProjectRequirement();
					requirement.setRequirementId(requirmentId);
					requirement.setProjectId(entity.getId());
					busProjectRequirmentMapper.insert(requirement);
				}
			}
		}
		return result;
	}
	
	@OperationLog(title = "修改项目", content = "'项目名称：' + #entity.getProjectName()", operationType = "2")
	@Override
    public int update(BusProject entity) throws Exception {
		int result = busProjectMapper.updateById(entity);
		if (result > 0){
			busProjectMilestoneMapper.deleteByProjectId(entity.getId());
			for(BusProjectMilestone milestone : entity.getMilestones()){
				milestone.setProjectId(entity.getId());
				busProjectMilestoneMapper.insert(milestone);
			}
			busProjectMemberMapper.deleteByProjectId(entity.getId());
			for(BusProjectMember member : entity.getMembers()){
				for(Integer userId : member.getUserIdArr()){
					BusProjectMember newMember = new BusProjectMember();
					newMember.setMemberType(member.getMemberType());
					newMember.setUserId(userId);
					newMember.setProjectId(entity.getId());
					busProjectMemberMapper.insert(newMember);
				}
			}
			busProjectRequirmentMapper.deleteByProjectId(entity.getId());
			if (null != entity.getRequirments()){
				for(Integer requirmentId : entity.getRequirments()){
					BusProjectRequirement requirement = new BusProjectRequirement();
					requirement.setRequirementId(requirmentId);
					requirement.setProjectId(entity.getId());
					busProjectRequirmentMapper.insert(requirement);
				}
			}
		}
		return result;
	}
	
	// 生成项目编码
	private String generateCode(String key){
		String requestId = UUID.randomUUID().toString();
		int seq = 1;
		boolean isReleaseLock = true; // 是否释放锁
		String lockKey = key + "_lock";
		try {
			boolean mLock = redisUtil.lock(requestId, lockKey, 1 * 10);//锁的有效时间10秒
			if(mLock){
				isReleaseLock = false;
				seq = (int) redisUtil.incrKey(key, 1, getNowToNextDayMilliseconds(), TimeUnit.SECONDS);
				redisUtil.releaseLock(requestId, lockKey);//释放锁
				isReleaseLock = true;
			}
		} catch (Exception e) {

		}finally{
			if(!isReleaseLock){
				redisUtil.releaseLock(requestId, lockKey);
			}
		}
		LocalDate now = LocalDate.now();
		String code = CODE_PREFIX + now.format(DateTimeFormatter.ofPattern("yyyyMMdd")) + seq;
		return code;
	}
	
	// 今日剩余时间计算
    private Long getNowToNextDayMilliseconds() {
        //获取当前时间
        Calendar calendar = Calendar.getInstance();
        //当前天+1
        calendar.add(Calendar.DAY_OF_YEAR, 1);
        //将时分秒毫秒都设为0
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        //减去当前时间获取插值
        return (calendar.getTimeInMillis() - System.currentTimeMillis());
    }
    
    @Override
    public BusProject getByWorkId(int workId) {
    	BusProject project = busProjectMapper.selectByWorkId(workId);
    	List<BusProjectMilestone> milestones = busProjectMilestoneMapper.selectByProjectId(project.getId());
		if (milestones != null){
			project.setMilestones(milestones.toArray(new BusProjectMilestone[0]));
		}
		List<BusProjectMember> members = busProjectMemberMapper.selectByProjectId(project.getId());
		if (members != null){
			project.setMembers(members.toArray(new BusProjectMember[0]));
		}
		List<BusRequirement> requirements = busProjectRequirmentMapper.selectByProjectId(project.getId());
		if (requirements != null){
			project.setRequirmentList(requirements.toArray(new BusRequirement[0]));
			requirements.stream().map(s -> s.getId()).collect(Collectors.toList());
			project.setRequirments(requirements.stream().map(s -> s.getId()).collect(Collectors.toList()).toArray(new Integer[0]));
		}
		return project;
    }
}
